package com.webframe.web.controller;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.webframe.constant.WFConstant;
import com.webframe.service.def.ITableOperationService;
import com.webframe.util.UUIDGenerator;

/**
 * 类功能描述：插入数据到数据库表中，TableInsertController必须在Spring配置文件中使用原型 <bean id="editGridController"
 * class="com.berheley.bi.web.controller.EditGridController" scope="prototype"> <property
 * name="jdbcDao" ref="jdbcDao"></property> </bean>
 * 
 *         Description:
 */
@Controller
@RequestMapping("/tableInsert")
public class TableInsertController extends BaseController
{

	@Autowired
	private ITableOperationService	tableOperationService;

	@SuppressWarnings({"unchecked", "rawtypes"})
	@RequestMapping(method = RequestMethod.POST)
	protected ModelAndView index(HttpServletRequest request, HttpServletResponse response)
	{
		String succesePage = request.getParameter(WFConstant.Constant_Success_PAGE_);
		String errorPage = request.getParameter(WFConstant.Constant_Error_PAGE_);
		String isAjax = request.getParameter(WFConstant.IS_AJAX_);
		String targetPage = succesePage;
		Map params = request.getParameterMap();
		Iterator it = params.keySet().iterator();
		Map object = new HashMap();
		Object tmp;
		while (it.hasNext())
		{
			tmp = it.next();
			if (((Object[]) params.get(tmp)).length > 1) // 页面有多个相同的name值，以数组的形式获得，以#号分隔的字符串保存到数据库
			{
				int params_length = ((Object[]) params.get(tmp)).length;
				StringBuffer params_value = new StringBuffer();
				for (int i = 0; i < params_length; i++)
				{
					params_value.append("#" + ((Object[]) params.get(tmp))[i].toString());
				}
				object.put(tmp, params_value.substring(1));
			} else
			{
				object.put(tmp, ((Object[]) params.get(tmp))[0]);
			}
		}
		if (submissionPermission(request))
		{
			try
			{
				tableOperationService.doInsertOrUpdateExecute(object);
			} catch (Exception e)
			{
				e.printStackTrace();
			}
		}
		if ("true".equalsIgnoreCase(isAjax))
		{
			StringBuffer sb = new StringBuffer();
			Set keys = object.keySet();
			sb.append("{");
			for (Iterator iterator = keys.iterator(); iterator.hasNext();)
			{
				String key = (String) iterator.next();
				sb.append(key);
				sb.append(":'");
				sb.append(object.get(key));
				sb.append("'");
				if (iterator.hasNext())
				{
					sb.append(",");
				}
			}
			sb.append(",success:true}");
			outWrite(response, sb.toString());
			return null;
		} else
		{
			return new ModelAndView(targetPage, object);
		}
	}

	private boolean submissionPermission(HttpServletRequest request)
	{
		// 如果是Ajax请求，不处理重复提交
		if ("true".equalsIgnoreCase(request.getParameter(WFConstant.IS_AJAX_))) 
		{
			return true;
		}
		String key1 = request.getParameter(WFConstant.Constant_Duplicate_Submission_KEY_);
		String key2 = "";
		if (request.getSession().getAttribute(WFConstant.Constant_Duplicate_Submission_KEY_) != null)
		{
			key2 = request.getSession()
				.getAttribute(WFConstant.Constant_Duplicate_Submission_KEY_)
				.toString();
		}
		request.getSession()
			.setAttribute(WFConstant.Constant_Duplicate_Submission_KEY_,
				UUIDGenerator.getUUID());// 处理重复提交
		return (key1.equals(key2));
	}
}
